/*
 * @Author: liyin 2179253556@qq.com
 * @Date: 2025-09-25 14:45:45
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-09-25 14:46:15
 * @FilePath: \new-face-ordering-data-screen\src\directives\seamlessScroll.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import type { DirectiveBinding } from 'vue'

interface ScrollElement extends HTMLElement {
  timer?: any
  hoverStop?: boolean
}

interface ScrollOptions {
  step?: number
  interval?: number
  hoverStop?: boolean
  mode?: 'fixed' | 'continuous' // 新增：滚动模式（固定高度/连续1px）
}

export default {
  mounted(el: ScrollElement, binding: DirectiveBinding<ScrollOptions>) {
    const scrollBox = el
    // Check if there's at least one child element
    if (el.children.length === 0) {
      console.error('v-seamlessScroll: Element has no child elements to scroll')
      return
    }
    const scrollContent = el.children[0] as HTMLElement
    // Check if scrollContent is valid
    if (!scrollContent) {
      console.error('v-seamlessScroll: Child element is undefined')
      return
    }
    const options = binding.value || {}
    const step = options.step || 50
    const interval = options.interval || 3000
    const hoverStop = options.hoverStop ?? true
    const mode = options.mode || 'fixed' // 默认固定高度模式

    const scroll = () => {
      // Add check for scrollContent validity before accessing offsetHeight
      if (!scrollContent) return

      if (scrollContent.offsetHeight > scrollBox.offsetHeight) {
        let scrollTop = scrollBox.scrollTop
        if (scrollTop >= scrollContent.offsetHeight - scrollBox.offsetHeight) {
          scrollBox.scrollTop = 0 // 滚动到底部后回到顶部
        } else {
          if (mode === 'fixed') {
            // 固定高度模式：按step跳跃滚动（原逻辑）
            scrollBox.scrollTo({
              top: scrollTop + step,
              behavior: 'smooth'
            })
          } else {
            // 连续1px模式：每次滚动1px（无平滑动画保证连续性）
            scrollBox.scrollTop = scrollTop + 1
          }
        }
      }
    }

    const startScroll = () => {
      // 连续模式使用更短的间隔（10ms），固定模式使用原interval
      const scrollInterval = mode === 'continuous' ? interval : interval
      el.timer = setInterval(scroll, scrollInterval)
    }

    const stopScroll = () => {
      el.timer && clearInterval(el.timer)
    }

    if (hoverStop) {
      scrollBox.addEventListener('mouseenter', stopScroll)
      scrollBox.addEventListener('mouseleave', startScroll)
    }

    startScroll()
    el.hoverStop = hoverStop
  },

  unmounted(el: ScrollElement) {
    el.timer && clearInterval(el.timer)
    if (el.hoverStop) {
      el.removeEventListener('mouseenter', () => { })
      el.removeEventListener('mouseleave', () => { })
    }
  }
}